import type { RouteRecordRaw } from 'vue-router'

const loadLocalRouters = () => {
  // 动态添加路由
  const localRouters: RouteRecordRaw[] = []

  //读取router/home所有ts文件
  const routerMenu: Record<string, any> = import.meta.glob('../router/home/**/*.ts', {
    eager: true,
  })
  for (const key in routerMenu) {
    const module = routerMenu[key]
    localRouters.push(module.default)
  }
  return localRouters
}
export let firstMenu: any = null

export function mapMenusToRouter(userMenus: any[]) {
  const localRouter = loadLocalRouters()

  //根据菜单匹配正确的路由
  const routes: any = []
  for (const menu of userMenus) {
    for (const submenu of menu.children) {
      const route = localRouter.find((item) => item.path === submenu.url)
      if (route) {
        if (!routes.find((item) => item.path === menu.path)) {
          routes.push({ path: menu.url, redirect: route.path })
        }
        routes.push(route)
      }
      if (!firstMenu && route) firstMenu = submenu
    }
  }
  return routes
}

/**
 * 根据路径匹配菜单
 * @param path 当前路径
 * @param userMenu 所有菜单路径
 */
export function mapPathToMenu(path: any, userMenu: any[]) {
  for (const menu of userMenu) {
    for (const submenu of menu.children) {
      if (submenu.url === path) {
        return submenu
      }
    }
  }
}

/**
 * 根据路径匹配面包屑
 * @param path 当前路径
 * @param userMenu 所有菜单路径
 */
export function mapPathToBreadcrumbs(path: any, userMenu: any[]) {
  const breadcrmbs: any[] = []
  for (const menu of userMenu) {
    for (const submenu of menu.children) {
      if (submenu.url === path) {
        breadcrmbs.push({ name: menu.name, path: menu.url })
        breadcrmbs.push({ name: submenu.name, path: submenu.url })
      }
    }
  }
  return breadcrmbs
}
